package com.it.hanzhongtravelv1.service;

import com.it.hanzhongtravelv1.dto.CulturalActivityDTO;
import com.it.hanzhongtravelv1.dto.CulturalActivityDetailDTO;
import com.it.hanzhongtravelv1.entity.CulturalActivity;
import com.it.hanzhongtravelv1.entity.CulturalActivityDetail;
import com.it.hanzhongtravelv1.repository.CulturalActivityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CulturalActivityService {

    @Autowired
    private CulturalActivityRepository culturalActivityRepository;

    public List<CulturalActivityDTO> getAllActivities() {
        // Sort by startDate to ensure chronological order
        List<CulturalActivity> activities = culturalActivityRepository.findAllByOrderByStartDateAsc();
        return activities.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public CulturalActivityDTO saveActivity(CulturalActivity activity) {
        // 当保存CulturalActivity时，也级联保存其details
        if (activity.getDetails() != null) {
            for (CulturalActivityDetail detail : activity.getDetails()) {
                detail.setCulturalActivity(activity);
            }
        }
        CulturalActivity savedActivity = culturalActivityRepository.save(activity);
        return convertToDTO(savedActivity);
    }

    public void deleteActivity(Long id) {
        culturalActivityRepository.deleteById(id);
    }

    private CulturalActivityDTO convertToDTO(CulturalActivity activity) {
        CulturalActivityDTO dto = new CulturalActivityDTO();
        dto.setId(activity.getId());
        dto.setTitle(activity.getTitle());
        dto.setMainDescription(activity.getMainDescription());
        dto.setImage(activity.getImage());
        dto.setLocation(activity.getLocation());
        dto.setDisplayDate(activity.getDisplayDate());
        dto.setParticipationMethod(activity.getParticipationMethod());
        
        List<CulturalActivityDetailDTO> detailDTOs = activity.getDetails().stream()
                .map(this::convertDetailToDTO)
                .collect(Collectors.toList());
        dto.setDetails(detailDTOs);

        dto.setStartDate(activity.getStartDate());
        dto.setEndDate(activity.getEndDate());

        return dto;
    }

    private CulturalActivityDetailDTO convertDetailToDTO(CulturalActivityDetail detail) {
        CulturalActivityDetailDTO dto = new CulturalActivityDetailDTO();
        dto.setSubtitle(detail.getSubtitle());
        dto.setContent(detail.getContent());
        return dto;
    }
} 